<?php
if (!ob_start("ob_gzhandler")) {
  ob_start();
}

require_once '../include/config.php';
require_once '../include/utils.class.php';
require_once '../include/orm.class.php';

$__sys = Utils::get_param('__sys', NULL);
$__inst = Utils::get_param('__inst', NULL);

$session_id = Utils::get_param('PHPSESSID', NULL);

if ($session_id) {
  session_id($session_id);
  session_start();
} else {
  session_name(SESSION);
  session_start();
}

if (!isset($_SESSION[SYS . $__sys])) {
  die('Session Not Found');
}

$app_data = $_SESSION[SYS . $__sys];
$inst = $app_data->instances[$__inst];

if (!in_array($inst->__folder, $app_data->plugins)) {
  die('Acceess Denied');
}

if ($app_data->sys->login_required == 1 && (!(isset($app_data->is_authorised)) || $app_data->is_authorised == 0) && !in_array($inst->__folder, $app_data->exceptions)) {
  die('Not Authenticated');
}

$path = Utils::get_param('p', NULL);
$name = Utils::get_param('n', NULL);

if (file_exists($path)) {
  if ($__sys != 'admin') {
    $orm = new ORM();
    $opts = new stdClass();
    $opts->cd = 't.link = :v1';
    $opts->cdv = array(':v1' => $path);
    $opts->sel = 't.*, t1.category_id AS __category_id, t1.id AS __id';
    $opts->jt = 'LEFT JOIN pb_ht_article AS t1 ON t1.track_id = t.article_track_id';
    $data = $orm->get('pb_ht_article_file', NULL, NULL, NULL, NULL, $opts)->d;
    
    if (count($data) == 0) {
      die('The file may be deleted');
      return;
    }
    
    if ($data[0]->__category_id == USERONLY && (!isset($_SESSION[SYS . $__sys]->is_authorised) || $_SESSION[SYS . $__sys]->is_authorised == 0)) {
      header('location: ' . URL . HOME_DIR . $__sys . '.php?i=' . $app_data->__login_id . '&u=' . urlencode(URL . HOME_DIR . $__sys . '.php?i=' . ART_ID . '&__file=index_article&id=' . $data[0]->__id));
      return;
    }
    
    if ($data[0]->__category_id == PAYNEED) {
      header('location: ' . URL . HOME_DIR . $__sys . '.php?i=' . CONTACT_ID . '&t=' . urlencode('我想要下载收费文件' . $name));
      return;
    }
  }

  $file = fopen($path, "r");
  Header("Content-type: application/octet-stream");
  Header("Accept-Ranges: bytes");
  Header("Accept-Length:" . filesize($path));
  Header("Content-Disposition: attachment; filename=\"" . $name . "\"");
  echo fread($file, filesize($path));
  fclose($file);
  exit;
}
?>